package ewan.android.droidjockey;


import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import ewan.android.droidjockey.R;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils.TruncateAt;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Settings extends Activity {

	Button nowPlaying;
	ProgressBar progress;
	TextView text;
	EditText email;
	EditText password;

	CheckBox songInfo;
	CheckBox concerts;
	CheckBox emails;
	CheckBox news;

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
		text = (TextView) findViewById(R.id.textView1);
		email = (EditText) findViewById(R.id.email);
		password = (EditText) findViewById(R.id.password);

		songInfo = (CheckBox) findViewById(R.id.songintrobox);
		concerts = (CheckBox) findViewById(R.id.concertbox);
		emails = (CheckBox) findViewById(R.id.mailbox);
		news = (CheckBox) findViewById(R.id.newsbox);

		nowPlaying = (Button) findViewById(R.id.now_playing);
		nowPlaying.setSelected(true);
		nowPlaying.setEllipsize(TruncateAt.MARQUEE);
		nowPlaying.setSingleLine(true);
		progress = (ProgressBar) findViewById(R.id.progress);
		try {
			load();
			progress.setMax((int) MusicRetriever.getCurrentSong().getDuration());
		} catch (Exception e) {
		}
		// }
		nowPlaying.setOnClickListener(new OnClickListener() {

			public void onClick(View target) {

				if (target == nowPlaying) {
					try {
						save();
					} catch (Exception e) {
						e.printStackTrace();
					}
					Intent intent = new Intent();
					setResult(1, intent);
					finish();
				}

			}
		});
		if (!thread.isAlive()) {
			thread.start();
		}

	}

	Thread thread = new Thread() {
		public synchronized void run() {

			while (true) {
				try {

					while (MusicService.State.Playing != null) {

						try {
							Message position = new Message();
							position.what = MusicService.mPlayer
									.getCurrentPosition();
							threadHandler.sendMessage(position);
							if (MusicService.State.Playing != null) {
								if (!nowPlaying.getText().equals(
										MusicRetriever.getCurrentSong()
												.getTitle().toString())) {

									Message update = new Message();
									update.what = 0;
									UIHandler.sendMessage(update);

								}
							}
						} catch (NullPointerException e) {
						} catch (Exception e) {
							e.printStackTrace();
						}
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							Thread.currentThread().interrupt();
							break;
						}
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						Thread.currentThread().interrupt();
						break;
					}
				} catch (IndexOutOfBoundsException e) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
						Thread.currentThread().interrupt();
						break;
					}
				}
			}
		}

	};

	public Handler UIHandler = new Handler() {

		public synchronized void handleMessage(Message msg) {
			if (msg.what == 0) {
				try {
					progress.setMax((int) MusicRetriever.getCurrentSong()
							.getDuration());
				} catch (Exception e) {
				}
			}
		}
	};

	private Handler threadHandler = new Handler() {

		public synchronized void handleMessage(Message msg) {
			try {
				progress.setProgress(msg.what);
			} catch (NullPointerException e) {
			}
		}
	};

	public synchronized void onDestroy() {
		super.onDestroy();
		thread.interrupt();
	}

	public void save() throws Exception {

		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString("gmail", email.getText().toString());
		editor.putString("password", encrypt("ThisIsMyEncryptionSeed", password.getText().toString()));
		editor.putBoolean("songInfoChecked", songInfo.isChecked());
		editor.putBoolean("newsChecked", news.isChecked());
		editor.putBoolean("emailsChecked", emails.isChecked());
		editor.putBoolean("concertsChecked", concerts.isChecked());
		editor.commit();
	}

	public void load() throws Exception{
		
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		email.setText(sharedPreferences.getString("gmail", ""));
		password.setText(decrypt("ThisIsMyEncryptionSeed", (sharedPreferences.getString("password", ""))));
		songInfo.setChecked(sharedPreferences.getBoolean("songInfoChecked", true));
		news.setChecked(sharedPreferences.getBoolean("newsChecked", true));
		emails.setChecked(sharedPreferences.getBoolean("emailsChecked", true));
		concerts.setChecked(sharedPreferences.getBoolean("concertsChecked", true));
	}
	
	 public static String encrypt(String seed, String cleartext) throws Exception {
         byte[] rawKey = getRawKey(seed.getBytes());
         byte[] result = encrypt(rawKey, cleartext.getBytes());
         return toHex(result);
 }
 
 public static String decrypt(String seed, String encrypted) throws Exception {
         byte[] rawKey = getRawKey(seed.getBytes());
         byte[] enc = toByte(encrypted);
         byte[] result = decrypt(rawKey, enc);
         return new String(result);
 }

 private static byte[] getRawKey(byte[] seed) throws Exception {
         KeyGenerator kgen = KeyGenerator.getInstance("AES");
         SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
         sr.setSeed(seed);
     kgen.init(128, sr); // 192 and 256 bits may not be available
     SecretKey skey = kgen.generateKey();
     byte[] raw = skey.getEncoded();
     return raw;
 }

 
 private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
     SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
         Cipher cipher = Cipher.getInstance("AES");
     cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
     byte[] encrypted = cipher.doFinal(clear);
         return encrypted;
 }

 private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
     SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
         Cipher cipher = Cipher.getInstance("AES");
     cipher.init(Cipher.DECRYPT_MODE, skeySpec);
     byte[] decrypted = cipher.doFinal(encrypted);
         return decrypted;
 }

 public static String toHex(String txt) {
         return toHex(txt.getBytes());
 }
 public static String fromHex(String hex) {
         return new String(toByte(hex));
 }
 
 public static byte[] toByte(String hexString) {
         int len = hexString.length()/2;
         byte[] result = new byte[len];
         for (int i = 0; i < len; i++)
                 result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
         return result;
 }

 public static String toHex(byte[] buf) {
         if (buf == null)
                 return "";
         StringBuffer result = new StringBuffer(2*buf.length);
         for (int i = 0; i < buf.length; i++) {
                 appendHex(result, buf[i]);
         }
         return result.toString();
 }
 private final static String HEX = "0123456789ABCDEF";
 private static void appendHex(StringBuffer sb, byte b) {
         sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
 }

}
